// import type {
//   HttpProvider,
//   IReqJsonRpc,
//   IRsponseData,
// } from "@monorepo/shared/hooks/http/types";
import { showErrorToast } from ".";

const BaseUrl = "http://localhost:9527/api/rpc/v1/";

/** 封装uniapp的uni.request 方法为访问RPC服务
 *
 * @param data - 需要发送的数据JsonRPC请求体，根据需要调用 createRPCRequestBody 或者 createRestRequestBody
 * @param loadingTitle - 显示的loading标题，默认为空
 * @returns Promise<IRsponseData<T>>
 */
const RPCRequest = <T>(
  data: IReqJsonRpc,
  onDone?: <T>(Data: T) => void,
  onBusError?: (error: any) => void,
  onSvcError?: (error: any) => void
): Promise<IRsponseData<T>> => {
  return new Promise((resolve, reject) => {
    uni.request({
      method: "POST",
      url: BaseUrl,
      // header: {
      //   'authorization': 'Bearer ' + AppGlobal.value.shopToken
      // },
      data,
      success: (res) => {
        console.log(res);

        if (res.statusCode === 200) {
          const data = res.data as IRsponseData<T>;
          if (onDone) {
            onDone(data.data);
          }
          if (data.code === 200) resolve(data);
          else reject(data);
        } else {
          reject(res.data as IRsponseData<null>);
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

/**
 * ### 封装uniapp的uni.request 方法为访问RPC服务
 *
 *
 * @param params - 请求参数
 * @param onDone - 请求成功回调
 * @param onBusError - 业务错误回调
 * @param onSvcError - 服务端错误回调
 */
export const uniRequestPrivoder: HttpProvider = <T>(
  params: IReqJsonRpc,
  onDone?: <T>(Data: T) => void,
  onBusError?: (error: any) => void,
  onSvcError?: (error: any) => void
) => {
  uni.request({
    method: "POST",
    url: BaseUrl,
    // header: {
    //   'authorization': 'Bearer ' + AppGlobal.value.shopToken
    // },
    data: params,
    success: (res) => {
      if (res.statusCode === 200) {
        const data = res.data as IRsponseData<T>;
        if (data.code === 200) {
          if (onDone) onDone(data.data);
        } else {
          showErrorToast(data.msg);
          if (onBusError) onBusError(data);
        }
      } else {
        showErrorToast("服务器异常");
        if (onSvcError) onSvcError(res.data);
      }
    },
    fail: (err) => {
      showErrorToast("网络异常");
      if (onSvcError) onSvcError(err);
    },
  });
};
